package com.kfm.servlet;

import com.kfm.control.JdbcSelect;
import com.kfm.tool.ServerFile;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/uploadFile")
@MultipartConfig
public class UploadFile extends HttpServlet {
    @SneakyThrows
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //
        //设置编码
        request.setCharacterEncoding("utf-8");
        Part part = request.getPart("myfile");
        //通过Part对象获取文件名
        String fileName = part.getSubmittedFileName();
        String fileType = fileName.split("\\.")[1];
        //获取路径
        String filePath = request.getServletContext().getRealPath("/");
        String filpathcomplete = filePath + fileName;
        System.out.println(filpathcomplete);
        part.write(filpathcomplete);
        String sql = "insert into fileta (file_path,file_type)values(?,?)";
        //插入日志
        JdbcSelect.insertiofo(sql, filpathcomplete, fileType);
        //关闭流
        JdbcSelect.close();
        //上穿至服务器
        ServerFile.uplod(filePath,fileName);
        response.sendRedirect("/servlet.html");
    }
}
